package com.hopster;

import java.sql.Date;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.ToggleButton;

public class CreateEvent extends Activity
{

    private Button startDate, startTime, endDate, endTime, alarmEnable, addAlarm, save,discard, /*map button*/map;
	private EditText name, description, location;
    private int button;	//0 is startDate, 1 is endDate, 2 is starTime, 3 is endTime, if -1 do all
    
	private int sYear, eYear;
    private int sMonth, eMonth;
    private int sDay, eDay;
    private int sWeekDay, eWeekDay;
    private Date curDate;
    
    private int sHour;
    private int sMinute;
    private int eHour;
    private int eMinute;
    private static int	time;
    
    static String[] daysOfWeek = {"", "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"};
    static String[] dayNight = {"AM", "PM"};
    
    static final int SDATE_DIALOG_ID = 0;
    static final int EDATE_DIALOG_ID = 1;
    static final int STIME_DIALOG_ID = 2;
    static final int ETIME_DIALOG_ID = 3;
    //static final int MAP_DIALOG_ID = 4;
    
    /*--------------------------------------------------------------------------------------*/ 
   	private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
	private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
	protected LocationManager locationManager;
	protected Button retrieveLocationButton;
	private static String lng = "", lat = "";
	/*--------------------------------------------------------------------------------------*/ 
    
    protected void onCreate(Bundle savedInstanceState) 
    { 		
    	/*--------------------------------------------------------------------------------------*/ 	
    	 retrieveLocationButton = (Button) findViewById(R.id.mapbutton);        
         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

         	        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         	        locationManager.requestLocationUpdates(
         		    LocationManager.GPS_PROVIDER,
         		               MINIMUM_TIME_BETWEEN_UPDATES,
         		               MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
         		               new MyLocationListener());
    	/*--------------------------------------------------------------------------------------*/
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_event);
        
        //Intake calendar date info
        Bundle date = getIntent().getExtras();
        int dday = date.getInt("day");
        int dmonth = date.getInt("month");
        int dyear = date.getInt("year");
        int dwkday = date.getInt("wkday");

        // capture our View elements (4 buttons)
        name		= (EditText) findViewById(R.id.editText1);
        description	= (EditText) findViewById(R.id.editText3);
        location	= (EditText) findViewById(R.id.editText2);
        startDate	= (Button) findViewById(R.id.pickStartDate);
		startTime	= (Button) findViewById(R.id.pickStartTime);
		endDate	 	= (Button) findViewById(R.id.pickEndDate);
		endTime		= (Button) findViewById(R.id.pickEndTime);
		alarmEnable = (Button) findViewById(R.id.alarmEnable);
		addAlarm	= (Button) findViewById(R.id.addAlarm);
		save 		= (Button) findViewById(R.id.save);
		discard 	= (Button) findViewById(R.id.discard);
		/*mapbutton*/
		map = (Button) findViewById(R.id.mapbutton);
		
		addAlarm.setEnabled(false);
//Date and Time
        // get the current date
		        final Calendar c = Calendar.getInstance();
		        curDate = new Date(sYear, sMonth, sDay);
		        
		        
		        sYear = dyear;
		        sMonth = dmonth;
		        sDay = dday;
		        sWeekDay = dwkday;
		        
		        eYear = dyear;
		        eMonth = dmonth;
		        
		        eDay = dday;
		        eWeekDay = dwkday;
		        
		        sHour = c.get(Calendar.HOUR_OF_DAY);
		        sMinute = c.get(Calendar.MINUTE);
		        
		        eHour = c.get(Calendar.HOUR_OF_DAY);
		        eMinute = c.get(Calendar.MINUTE);
		        
		        button = -1;
		        updateDisplay();
		       
		// add a click listener to the button
/*--------------------------------------------------------------------------------------*/ 	
		map.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				button = 4;
				Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				
		 	       if(loc != null){
		     	        lng = loc.getLongitude() + "";
		     	        lat = loc.getLatitude() + "";
		 	       }
		 	       else{
		 	    	    lng = 29.648367 + "";
		 	    	    lat = -82.344439 + "";
		 	       }
		 	      final Intent intent = new Intent(Intent.ACTION_VIEW,
		       	       /* Using the web based turn by turn directions url. */
		       	       Uri.parse(
		       	                "http://maps.google.com/maps?" +
		       	                /*device longitude and latitude*/
		       	                "saddr=" + lng + "," + lat +
		       	                /*event address goes below*/
		       	                "&daddr=" + location.getText().toString()));
		       	       startActivity(intent);
			}
		
		});        
/*--------------------------------------------------------------------------------------*/ 	
		        
        startDate.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {	
				button = 0;
                showDialog(SDATE_DIALOG_ID);
            }
        });
		
		endDate.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {	
				button = 1;
                showDialog(EDATE_DIALOG_ID);
            }
        });

		startTime.setOnClickListener(new View.OnClickListener() 
		{
            public void onClick(View v) 
            {
            	button = 2;
                showDialog(STIME_DIALOG_ID);
            }
        });
		
		endTime.setOnClickListener(new View.OnClickListener() 
		{
            public void onClick(View v) 
            {
            	button = 3;
                showDialog(ETIME_DIALOG_ID);
            }
        });
		
//Alarm		
		alarmEnable.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {	
				if(((ToggleButton)alarmEnable).isChecked())
				{
					addAlarm.setEnabled(true);
				}
				else
				{
					addAlarm.setEnabled(false);
				}
            }
        });	
		addAlarm.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				Intent i = new Intent();
        		i.setClassName("com.hopster", "com.hopster.CreateAlarm");
        		startActivity(i);
			}
		});
		
//Discard 
		discard.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				finish();
			}
		});

//Save
		save.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				String eventName = name.getText().toString();
				String eventDescription = description.getText().toString();
				String eventLocation = location.getText().toString();

				Calendar startCalendar = Calendar.getInstance();
				startCalendar.set(sYear, sMonth, sDay, sHour, sMinute);
				
				Calendar endCalendar = Calendar.getInstance();
				endCalendar.set(eYear, eMonth, eDay, eHour, eMinute);
				
				Event eventToAdd = new Event(eventName, eventDescription, eventLocation, startCalendar, endCalendar);
				
				EventService es = EventService.getInstance();
				boolean success = es.addEvent(eventToAdd);
				
				if(!success)
				{
					new AlertDialog.Builder(CreateEvent.this).setTitle("Error!").setMessage("An event with this name already exists. Please change the name of the event.").setNeutralButton("Close", null).show();
				}
				else
				{
					finish();
				}
			}
		});
    }
    
    
    // updates the date in the TextView
    private void updateDisplay() 
    {	
		if(button == -1)
		{
			startDate.setText(	new StringBuilder()
								// Month is 0 based so add 1
								.append(daysOfWeek[sWeekDay] + " ")
								.append(sMonth + 1).append("/")
								.append(sDay).append("/")
								.append(sYear).append(" "));
			endDate.setText(	new StringBuilder()
								// Month is 0 based so add 1
								.append(daysOfWeek[eWeekDay] + " ")
								.append(eMonth + 1).append("/")
								.append(eDay).append("/")
								.append(eYear).append(" "));
			
			startTime.setText(	new StringBuilder()
								.append(" " + getHour(sHour)).append(":")
								.append(pad(sMinute) + " ").append(dayNight[getPeriod(eHour)]));
			
			endTime.setText(	new StringBuilder()
								.append(" " + getHour(eHour)).append(":")
								.append(pad(eMinute) + " ").append(dayNight[getPeriod(eHour)]));
		}
    	else if(button == 0)
        {
			startDate.setText(	new StringBuilder()
								// Month is 0 based so add 1
								.append(daysOfWeek[sWeekDay] + " ")
								.append(sMonth + 1).append("/")
								.append(sDay).append("/")
								.append(sYear).append(" "));
		}
		else if(button == 1)
		{
			endDate.setText(	new StringBuilder()
								// Month is 0 based so add 1
								.append(daysOfWeek[eWeekDay] + " ")
								.append(eMonth + 1).append("/")
								.append(eDay).append("/")
								.append(eYear).append(" "));
		}
		else if(button == 2)
		{
			
			startTime.setText(	new StringBuilder()
			                		.append(" " + getHour(sHour)).append(":")
			                		.append(pad(sMinute) + " ").append(dayNight[getPeriod(sHour)]));
		}
		else if(button == 3)
		{
			endTime.setText(	new StringBuilder()
    							.append(" " + getHour(eHour)).append(":")
    							.append(pad(eMinute) + " ").append(dayNight[getPeriod(eHour)]));
		} 	
    }
    
    private static String pad(int c) 
    {
        if (c >= 10)
        {
            return String.valueOf(c);
        }
        else
        {
            return "0" + String.valueOf(c);
        }
    } 
    
    private static int getHour(int hour)
    {
    	if(hour == 0 || hour == 12)
    		return 12;
    	else
    		return hour%12;
    }
    private static int getPeriod(int hour)
    {
    	if(hour>=12 && hour<24)
    		time = 1;
    	else 
    		time = 0;
    	return time;
    }
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener sDateSetListener =
            new DatePickerDialog.OnDateSetListener() 
    		{

                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
                {
                	curDate = new Date(year, monthOfYear, dayOfMonth);
                	sYear = year;
                	sMonth = monthOfYear;
	                sDay = dayOfMonth;
	                sWeekDay = curDate.getDay();
	                updateDisplay();
                }
            };
            
    private DatePickerDialog.OnDateSetListener eDateSetListener =
            new DatePickerDialog.OnDateSetListener() 
    		{

                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
                {
                	curDate = new Date(year, monthOfYear, dayOfMonth);
                	eYear = year;
                	eMonth = monthOfYear;
	                eDay = dayOfMonth;
	                eWeekDay = curDate.getDay();
	                updateDisplay();
                }
            };            
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener sTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() 
    {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
            {
                sHour = hourOfDay;
                sMinute = minute;
                updateDisplay();
            }
        };     
        
    private TimePickerDialog.OnTimeSetListener eTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() 
    {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
            {
                eHour = hourOfDay;
                eMinute = minute;
                updateDisplay();
            }
        };
        
    @Override
    protected Dialog onCreateDialog(int id) 
    {
        switch (id) 
        {
	        case SDATE_DIALOG_ID:
	            	return new DatePickerDialog(this, sDateSetListener, sYear, sMonth, sDay);
	        case EDATE_DIALOG_ID:
	        		return new DatePickerDialog(this, eDateSetListener, eYear, eMonth, eDay);
	        case STIME_DIALOG_ID:
	        		return new TimePickerDialog(this, sTimeSetListener, sHour, sMinute, false);
	        case ETIME_DIALOG_ID:
	        		return new TimePickerDialog(this, eTimeSetListener, eHour, eMinute, false);
        }
        return null;
    }

}